package com.yuan.pay_mall;

import com.yuan.pay_mall.exception.UserLoginException;
import com.yuan.pay_mall.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.yuan.pay_mall.consts.MallConst.CURRENT_USER;

/**
 * 用户登录拦截器
 * 看用户是否登录
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    /**
     * true 表示继续流程，false 表示中断
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    //执行之前进行拦截，所以重写了方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("perHandler...");

        User user = (User)request.getSession().getAttribute(CURRENT_USER);
        if(user ==null){
            log.info("user ==null");
            //response.getWriter().print("error");
            throw new UserLoginException();
           // return false;拦截器中不要return了,直接抛出异常，然后捕获异常
//            return ResponseVo.error(NEED_LOGIN);
        }
        return true;
    }
}


